/**
 * @param {string} url
 * @returns {Object}
 */
function param2Obj(url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  if (!search) {
    return {}
  }
  const obj = {}
  const searchArr = search.split('&')
  searchArr.forEach(v => {
    const index = v.indexOf('=')
    if (index !== -1) {
      const name = v.substring(0, index)
      const val = v.substring(index + 1, v.length)
      obj[name] = val
    }
  })
  return obj
}

/**
 * This is just a simple version of deep copy
 * Has a lot of edge cases bug
 * If you want to use a perfect deep copy, use lodash's _.cloneDeep
 * @param {Object} source
 * @returns {Object}
 */
function deepClone(source) {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments', 'deepClone')
  }
  const targetObj = source.constructor === Array ? [] : {}
  Object.keys(source).forEach(keys => {
    if (source[keys] && typeof source[keys] === 'object') {
      targetObj[keys] = deepClone(source[keys])
    } else {
      targetObj[keys] = source[keys]
    }
  })
  return targetObj
}

function randomString(length = 5) {
  const CHARSET = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890~`!@#$%^&*()_-+=[{]}\|;:\'",<.>/?'

  const buf = Buffer.allocUnsafe(length)
  for (let i = 0; i < length; i++) {
    buf[i] = CHARSET.charCodeAt(Math.floor(Math.random() * CHARSET.length))
  }

  return buf.toString('utf8')
}

function formatDate(dt, fmt = 'yyyy-MM-dd HH:mm:ss') {
  dt = dt || new Date()
  var o = {
    'M+': dt.getMonth() + 1,
    'd+': dt.getDate(),
    'H+': dt.getHours(),
    'm+': dt.getMinutes(),
    's+': dt.getSeconds(),
    'q+': Math.floor((dt.getMonth() + 3) / 3),
    'S': dt.getMilliseconds()
  }

  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (dt.getFullYear() + '').substr(4 - RegExp.$1.length))
  }

  for (var k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      fmt = fmt.replace(RegExp.$1,
        (RegExp.$1.length === 1)
          ? (o[k])
          : (('00' + o[k]).substr(('' + o[k]).length)))
    }
  }

  return fmt
}

module.exports = {
  param2Obj,
  deepClone,
  randomString,
  formatDate
}
